<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vhall Stream Saver 测试页面</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }
        .test-section {
            margin: 20px 0;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .test-section h3 {
            margin-top: 0;
            color: #ffd700;
        }
        button {
            background: linear-gradient(45deg, #ff6b6b, #ee5a24);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }
        .status {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            font-weight: bold;
        }
        .success { background: rgba(46, 204, 113, 0.3); }
        .error { background: rgba(231, 76, 60, 0.3); }
        .info { background: rgba(52, 152, 219, 0.3); }
        .log {
            background: rgba(0, 0, 0, 0.3);
            padding: 15px;
            border-radius: 10px;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 14px;
            max-height: 300px;
            overflow-y: auto;
            margin: 10px 0;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .stream-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 15px;
            margin: 10px 0;
            border-radius: 10px;
            border-left: 4px solid #ffd700;
        }
        .quality-badge {
            display: inline-block;
            background: #ffd700;
            color: #333;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            margin: 2px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎥 Vhall Stream Saver 测试</h1>
        
        <div class="test-section">
            <h3>📡 模拟微吼流检测</h3>
            <p>点击按钮模拟微吼直播流的网络请求，测试插件的流检测功能。</p>
            <button onclick="simulateVhallStream()">模拟微吼流请求</button>
            <button onclick="simulateMultipleStreams()">模拟多个流</button>
            <button onclick="clearLog()">清空日志</button>
            <div id="streamStatus" class="status info">等待测试...</div>
        </div>

        <div class="test-section">
            <h3>🔍 检测到的流</h3>
            <div id="detectedStreams">
                <p>暂无检测到的流</p>
            </div>
        </div>

        <div class="test-section">
            <h3>📋 测试日志</h3>
            <div id="testLog" class="log">
                <div>测试页面已加载，等待操作...</div>
            </div>
        </div>

        <div class="test-section">
            <h3>🛠️ 插件状态检查</h3>
            <button onclick="checkExtensionStatus()">检查插件状态</button>
            <button onclick="testNativeHost()">测试 Native Host</button>
            <div id="extensionStatus" class="status info">点击按钮检查状态</div>
        </div>

        <div class="test-section">
            <h3>📖 使用说明</h3>
            <ol>
                <li>确保已在 Chrome 中加载了 Vhall Stream Saver 扩展</li>
                <li>点击"模拟微吼流请求"按钮测试流检测功能</li>
                <li>查看扩展图标是否显示检测到的流数量</li>
                <li>点击扩展图标打开弹窗查看检测到的流</li>
                <li>测试下载功能（需要配置 Native Host）</li>
            </ol>
        </div>
    </div>

    <script>
        let streamCounter = 0;
        const detectedStreams = [];

        function log(message, type = 'info') {
            const logDiv = document.getElementById('testLog');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.innerHTML = `[${timestamp}] ${message}`;
            logEntry.style.color = type === 'error' ? '#ff6b6b' : type === 'success' ? '#2ecc71' : '#74b9ff';
            logDiv.appendChild(logEntry);
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function updateStatus(elementId, message, type) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = `status ${type}`;
        }

        function simulateVhallStream() {
            streamCounter++;
            const streamId = `stream_${streamCounter}`;
            const qualities = ['1080p', '720p', '480p', '360p'];
            const randomQuality = qualities[Math.floor(Math.random() * qualities.length)];
            
            const streamData = {
                id: streamId,
                url: `https://live.vhall.com/v3/lives/watch/123456789?quality=${randomQuality}`,
                referer: 'https://live.vhall.com/',
                quality: randomQuality,
                title: `微吼直播流 ${streamCounter}`,
                timestamp: Date.now(),
                size: Math.floor(Math.random() * 500 + 100) + 'MB'
            };

            detectedStreams.push(streamData);
            
            // 模拟发送到扩展
            try {
                // 尝试与扩展通信
                if (typeof chrome !== 'undefined' && chrome.runtime) {
                    chrome.runtime.sendMessage('vhall-stream-saver-extension-id', {
                        type: 'STREAM_DETECTED',
                        data: streamData
                    }, (response) => {
                        if (chrome.runtime.lastError) {
                            log(`扩展通信失败: ${chrome.runtime.lastError.message}`, 'error');
                        } else {
                            log(`成功发送流数据到扩展: ${streamData.title}`, 'success');
                        }
                    });
                } else {
                    log('Chrome 扩展 API 不可用，这是正常的（在普通网页中）', 'info');
                }
            } catch (error) {
                log(`扩展通信错误: ${error.message}`, 'error');
            }

            // 模拟网络请求（这会被扩展的 webRequest 监听器捕获）
            fetch('/api/dispatch_replay', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Referer': 'https://live.vhall.com/',
                    'Authorization': 'Bearer fake-token-for-testing'
                },
                body: JSON.stringify({
                    stream_url: streamData.url,
                    quality: streamData.quality,
                    room_id: '123456789'
                })
            }).catch(error => {
                // 这个请求会失败，但这是预期的，因为我们只是想触发 webRequest 监听器
                log(`模拟网络请求已发送: ${streamData.url}`, 'info');
            });

            updateStatus('streamStatus', `已模拟 ${streamCounter} 个流`, 'success');
            updateDetectedStreams();
            log(`模拟微吼流: ${streamData.title} (${streamData.quality})`, 'success');
        }

        function simulateMultipleStreams() {
            for (let i = 0; i < 3; i++) {
                setTimeout(() => simulateVhallStream(), i * 500);
            }
        }

        function updateDetectedStreams() {
            const container = document.getElementById('detectedStreams');
            if (detectedStreams.length === 0) {
                container.innerHTML = '<p>暂无检测到的流</p>';
                return;
            }

            container.innerHTML = detectedStreams.map(stream => `
                <div class="stream-item">
                    <strong>${stream.title}</strong>
                    <span class="quality-badge">${stream.quality}</span>
                    <br>
                    <small>URL: ${stream.url}</small>
                    <br>
                    <small>大小: ${stream.size} | 时间: ${new Date(stream.timestamp).toLocaleTimeString()}</small>
                </div>
            `).join('');
        }

        function checkExtensionStatus() {
            log('检查扩展状态...', 'info');
            
            // 检查是否在扩展环境中
            if (typeof chrome !== 'undefined' && chrome.runtime) {
                try {
                    chrome.runtime.sendMessage('test-message', (response) => {
                        if (chrome.runtime.lastError) {
                            updateStatus('extensionStatus', '扩展未安装或未启用', 'error');
                            log(`扩展状态检查失败: ${chrome.runtime.lastError.message}`, 'error');
                        } else {
                            updateStatus('extensionStatus', '扩展运行正常', 'success');
                            log('扩展状态检查成功', 'success');
                        }
                    });
                } catch (error) {
                    updateStatus('extensionStatus', `扩展检查错误: ${error.message}`, 'error');
                    log(`扩展检查错误: ${error.message}`, 'error');
                }
            } else {
                updateStatus('extensionStatus', '不在扩展环境中（正常）', 'info');
                log('当前在普通网页环境中，无法直接访问扩展 API', 'info');
            }
        }

        function testNativeHost() {
            log('测试 Native Host 连接...', 'info');
            
            // 这个测试只能在扩展环境中运行
            if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.sendNativeMessage) {
                try {
                    chrome.runtime.sendNativeMessage(
                        'com.vhall.stream.saver',
                        { command: 'CHECK_YTDLP' },
                        (response) => {
                            if (chrome.runtime.lastError) {
                                log(`Native Host 连接失败: ${chrome.runtime.lastError.message}`, 'error');
                            } else {
                                log(`Native Host 响应: ${JSON.stringify(response)}`, 'success');
                            }
                        }
                    );
                } catch (error) {
                    log(`Native Host 测试错误: ${error.message}`, 'error');
                }
            } else {
                log('Native Host 测试只能在扩展环境中运行', 'info');
            }
        }

        function clearLog() {
            document.getElementById('testLog').innerHTML = '<div>日志已清空...</div>';
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('测试页面初始化完成', 'success');
            log('请确保已安装并启用 Vhall Stream Saver 扩展', 'info');
            
            // 检查是否有扩展 API
            if (typeof chrome !== 'undefined' && chrome.runtime) {
                log('检测到 Chrome 扩展 API', 'success');
            } else {
                log('未检测到 Chrome 扩展 API（在普通网页中这是正常的）', 'info');
            }
        });

        // 监听来自扩展的消息
        if (typeof chrome !== 'undefined' && chrome.runtime) {
            chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
                log(`收到扩展消息: ${JSON.stringify(message)}`, 'success');
                sendResponse({ received: true });
            });
        }
    </script>
</body>
</html>